﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ASPDotNetSamples;
using com.paypal.soap.api;
using AjaxControlToolkit;

public partial class Front_ReviewOrder : BasePage
{
    ASPDotNetSamples.BasePage basepage = new ASPDotNetSamples.BasePage();
    private GetExpressCheckoutDetailsResponseType details;
    DataTable dtTemp = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        dtTemp = (DataTable)Session["dtTemp"];
        //setSecureProtocol(true);
        PayPalAPI api = new PayPalAPI();
        if (this.Token != null)
        {
            this.details = api.GetExpressCheckoutDetails(this.Token);
            if (!IsPostBack)
            {
                try
                {
                    Session["dtGift"] = null;                   
                    Session["username"] = Membership.GetUser().UserName.ToString();
                    if (Session["username"] != null)
                    {
                        selectProduct();
                        FillCrdeitAmount();
                    }
                }
                catch
                {
                }
                this.DataBind();
            }
        }
        else
        {


            Hashtable requesthash = new Hashtable();
            requesthash = (Hashtable)Session["setecrequest"];

            string returnURL = Request.Url.GetLeftPart(UriPartial.Authority) + Response.ApplyAppPathModifier("ReviewOrder.aspx") + "?" + Constants.PAYMENT_AMOUNT_PARAM + "=" + "" + "&" + Constants.PAYMENT_CURRENCY_PARAM + "=" + this.Currency + "&" + Constants.PAYMENT_ACTION_PARAM + "=" + this.PaymentAction;
            string cancelURL = returnURL.Replace("ReviewOrder", "OrderDetailNew");
            cancelURL += "&" + "DealID=" + Session["DealID"];
            requesthash.Add("returnURL", returnURL);
            requesthash.Add("cancelURL", cancelURL);


            SetExpressCheckoutResponseType response = api.SetExpressCheckout(requesthash, this.PaymentAction);
            /// TO DO, get the environment from session...

            string host = "www." + Session["stage"].ToString() + ".paypal.com";

            /// string host = "www." + Constants.ENVIRONMENT + ".paypal.com";

            Response.Redirect("https://" + host + "/cgi-bin/webscr?cmd=_express-checkout&" + Constants.TOKEN_PARAM + "=" + response.Token);
        }
    }
    public void FillCrdeitAmount()
    {
        try
        {
            var credit = new DealesDataContext();
            var Amount = credit.GetCreditAmount(new Guid(Membership.GetUser().ProviderUserKey.ToString()));
            double money = 0.0;
            double referMoney = 0.0;
            ViewState["RferAmount"] = money;
            lblCredit.Text = "(0)";
            lblCredit.Visible = false;
            Credit.Visible = false;
            foreach (var item in Amount)
            {
                if (item.amount.ToString() != "0")
                {
                    money = Convert.ToDouble(item.amount.ToString());
                    if (money > 0)
                    {
                        //  lblFinalPrice.Visible = true;
                        // lblFinalPrice.Text = "<b>Congratulations!</b> You have $" + money + " Zupons credit that will be applied to this purchase.";
                        lblCredit.Text = "(" + money + ")";
                        lblCredit.Visible = true;
                        Credit.Visible = true;
                    }
                    ViewState["RferAmount"] = money;
                    var referAmount = credit.GetReferAmount(new Guid(Membership.GetUser().ProviderUserKey.ToString()));
                    foreach (var items in referAmount)
                    {
                        if (items.ReferAmount != null)
                        {
                            referMoney = Convert.ToDouble(items.ReferAmount.ToString());
                            if ((money - referMoney) == 0.0)
                            {

                                lblFinalPrice.Visible = false;
                                lblCredit.Visible = false;
                                Credit.Visible = false;
                            }
                            else
                            {
                                //  lblFinalPrice.Visible = true;
                                //  lblFinalPrice.Text = "<b>Congratulations!</b> You have $" + (money - referMoney) + " Zupons credit that will be applied to this purchase.";
                                lblCredit.Text = "(" + (money - referMoney) + ")";
                                lblCredit.Visible = true;
                                Credit.Visible = true;
                            }
                            ViewState["RferAmount"] = (money - referMoney);
                        }
                    }
                }
            }

            double RferAmount = Convert.ToDouble(ViewState["RferAmount"].ToString());
            double TotalPrice = Convert.ToDouble(Session["TotalPrice"].ToString());
            if (TotalPrice > RferAmount)
            {
                Session["ReferAmount"] = Convert.ToDouble(ViewState["RferAmount"].ToString());
                Session["TotalPrice"] = Convert.ToDouble(Session["TotalPrice"].ToString()) - Convert.ToDouble(ViewState["RferAmount"].ToString());
                lblYourTotal.Text = Session["TotalPrice"].ToString();
                ViewState["CreditZero"] = null;
            }
            else
            {
                // Session["ReferAmount"] = Convert.ToDouble(ViewState["RferAmount"].ToString()) - Convert.ToDouble(Session["TotalPrice"].ToString());
                Session["ReferAmount"] = lblPrice.Text;
                lblYourTotal.Text = "0";
                Session["TotalPrice"] = "0";
                ViewState["CreditZero"] = 1;
            }

        }
        catch
        {
        }
    }
    public string GetDealID()
    {
        string CityID;
        string DealID = "0";
        if (Request.Cookies["CityID"] != null)
        {
            CityID = Request.Cookies["CityID"].Value;
            var sub = new DealesDataContext();
            var getDealID = sub.Select_DealByCityIDNew(Convert.ToInt32(CityID));
            foreach (var item in getDealID)
            {
                DealID = item.DealID.ToString();

            }
        }
        return DealID;
    }
    protected void lnkbtnCancel_Click(object sender, EventArgs e)
    {
        Session["DealID"] = GetDealID();
        if (Session["DealID"] != null)
        {
            Response.Redirect("~/Default.aspx?DealID=" + Session["DealID"].ToString());
        }
    }
    public void selectProduct()
    {
        txtQuantity.Enabled = false;
        txtQuantity.Text = Session["Quantity"].ToString();
        var a = new DealesDataContext();
        var query = a.SelectProduct_Deal(Convert.ToInt32(Session["DealID"]));
        foreach (var item in query)
        {
            lblDescription.Text = item.ShortDescription;
            lblPrice.Text = (System.Math.Round(double.Parse(item.SellPrice.ToString()), 2)).ToString();
            lblTotalPrice.Text = (Convert.ToDouble(lblPrice.Text) * Convert.ToDouble(txtQuantity.Text)).ToString();
            lblYourTotal.Text = (Convert.ToDouble(lblPrice.Text) * Convert.ToDouble(txtQuantity.Text)).ToString();
            Session["TotalPrice"] = lblTotalPrice.Text;
            Session["Price"] = lblPrice.Text;
            Session["Quantity"] = txtQuantity.Text;
        }
        lblCredit.Text = "(0)";
        lblCredit.Visible = false;
        Credit.Visible = false;
        var query2 = new DealesDataContext();
        var CheckQtyQuery = query2.Select_MaxQtyFromDeal(Convert.ToInt32(Session["DealID"].ToString()));
        int LimitPerPerson = 0;
        foreach (var j in CheckQtyQuery)
        {
            LimitPerPerson = Convert.ToInt32(j.limitperperson);
        }
        if (LimitPerPerson == 1)
        {
            txtQuantity.Enabled = false;
        }
    }
    public void setSecureProtocol(bool bSecure)
    {
        string redirectUrl = null;

        // if we want HTTPS and it is currently HTTP
        if (bSecure && !Request.IsSecureConnection)
            redirectUrl = Request.Url.ToString().Replace("http:", "https:");

        else

            // if we want HTTP and it is currently HTTPS
            if (!bSecure && Request.IsSecureConnection) redirectUrl = Request.Url.ToString().Replace("https:", "http:");

        //else

        // in all other cases we don't need to redirect

        // check if we need to redirect, and if so use redirectUrl to do the job
        if (redirectUrl != null)

            Response.Redirect(redirectUrl);

    }
    private string RequestPath
    {
        get
        {
            return InsertCookielessSessionUrl(Request.Path, Request.ApplicationPath);
        }
    }

    private string InsertCookielessSessionUrl(string path, string applicationPath)
    {

        return path.Replace(applicationPath, applicationPath + (Session.IsCookieless ? "/(" + Session.SessionID + ")" : string.Empty));
    }

    protected string PaymentAmount
    {
        get
        {
            double OrderAmount = (double.Parse(this.ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.PaymentDetails[0].OrderTotal.Value));

            return OrderAmount.ToString();

        }
    }

    protected string Token
    {
        get
        {
            return this.Request.QueryString.Get(Constants.TOKEN_PARAM);
        }
    }

    protected string FirstNameLiteralText
    {
        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.FirstName;
            return text;
        }
    }

    protected string LastNameLiteralText
    {
        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.LastName;
            return text;
        }
    }

    protected string StreetLiteralText
    {
        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1;
            dtTemp.Rows[0]["address1"] = text;
            return text;
        }
    }

    protected string CityLiteralText
    {
        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName;
            dtTemp.Rows[0]["city"] = text;
            return text;
        }
    }

    protected string StateLiteralText
    {
        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince;
            dtTemp.Rows[0]["state"] = text;
            return text;
        }
    }

    protected string PostalCodeLiteralText
    {
        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode;
            dtTemp.Rows[0]["Zip"] = text;
            return text;
        }
    }

    protected string CountryLiteralText
    {

        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName;
            return text;
        }
    }

    protected string ShippingCalculationModeLiteralText
    {

        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.UserSelectedOptions.ShippingCalculationMode;
            return text;
        }
    }
    protected string ShippingOptionAmountLiteralText
    {

        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.PaymentDetails[0].ShippingTotal.Value;
            return text;
        }
    }
    protected string ShippingOptionNameLiteralText
    {

        get
        {
            string text = ExpressCheckoutDetails.GetExpressCheckoutDetailsResponseDetails.UserSelectedOptions.ShippingOptionName;
            return text;
        }
    }
    protected CurrencyCodeType Currency
    {
        get
        {
            Hashtable requesthash = new Hashtable();
            requesthash = (Hashtable)Session["setecrequest"];
            string text = requesthash["currency"].ToString();

            return (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), text);
        }
    }

    protected GetExpressCheckoutDetailsResponseType ExpressCheckoutDetails
    {
        get
        {
            return this.details;
        }
    }




    protected void ECReceiptLink_Click(object sender, EventArgs e)
    {
        Session["dtTemp"] = dtTemp;
        //   Response.Redirect(Session["HttpsPath"].ToString()+"/ECReceipt.aspx?" + Constants.TOKEN_PARAM + "=" + this.Token + "&" + Constants.PAYERID_PARAM + "=" + this.details.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID
        // + "&" + Constants.PAYMENT_AMOUNT_PARAM + "=" + this.PaymentAmount + "&" + Constants.PAYMENT_CURRENCY_PARAM + "=" + this.Currency);
        Response.Redirect("ECReceipt.aspx?" + Constants.TOKEN_PARAM + "=" + this.Token + "&" + Constants.PAYERID_PARAM + "=" + this.details.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID
           + "&" + Constants.PAYMENT_AMOUNT_PARAM + "=" + this.PaymentAmount + "&" + Constants.PAYMENT_CURRENCY_PARAM + "=" + this.Currency);
    }
    protected void lnkBtnGift_Click(object sender, EventArgs e)
    {
        txtTo.Text = "";
        txtToEmail.Text = "";
        txtToEmail.Enabled = true;
        txtMessage.Text = "";
        rbtnDelivery.SelectedValue = "0";
        divAuthentication.Show();
    }
    protected void lnkbtnEditGift_Click(object sender, EventArgs e)
    {
        divAuthentication.Show();
        DataTable dtGift = (DataTable)Session["dtGift"];
        txtTo.Text = dtGift.Rows[0]["To"].ToString();
        txtFrom.Text = dtGift.Rows[0]["From"].ToString();
        txtMessage.Text = dtGift.Rows[0]["Message"].ToString();
        txtToEmail.Text = dtGift.Rows[0]["EmailTo"].ToString();
        rbtnDelivery.SelectedValue = dtGift.Rows[0]["Delivery"].ToString();
    }
    protected void imgGiftCancel_Click(object sender, ImageClickEventArgs e)
    {
        divAuthentication.Hide();
        Session["dtGift"] = null;
        EditGift.Visible = false;
        SaveGift.Visible = true;
    }
    protected void rbtnDelivery_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (rbtnDelivery.SelectedValue == "1")
        {
            txtToEmail.Enabled = false;
            txtToEmail.Text = "";
            lblGiftErr.Text = "";
        }
        else
            txtToEmail.Enabled = true;
    }
    protected void btnGiftSave_Click(object sender, EventArgs e)
    {
        if (rbtnDelivery.SelectedValue == "0")
        {
            if (txtToEmail.Text == "")
            {
                lblGiftErr.Text = "To Email is required.";
                return;
            }

        }
        DataTable dtGift = new DataTable();
        dtGift.Columns.Add("To");
        dtGift.Columns.Add("From");
        dtGift.Columns.Add("Message");
        dtGift.Columns.Add("Delivery");
        dtGift.Columns.Add("EmailTo");
        DataRow dr = dtGift.NewRow();
        dtGift.Rows.Add(dr);
        dtGift.Rows[0]["To"] = txtTo.Text.ToString();
        dtGift.Rows[0]["From"] = txtFrom.Text.ToString();
        dtGift.Rows[0]["Message"] = txtMessage.Text.ToString();
        dtGift.Rows[0]["Delivery"] = rbtnDelivery.SelectedValue.ToString();
        dtGift.Rows[0]["EmailTo"] = txtToEmail.Text.ToString();
        Session["dtGift"] = dtGift;
        lblGiftFor.Text = "<b>Gift For:</b> " + txtTo.Text;
        EditGift.Visible = true;
        SaveGift.Visible = false;
        divAuthentication.Hide();

    }
}
